package com.yunshipei;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.request.target.ViewTarget;
import com.yunshipei.common.Globals;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.core.manager.XCloudSDKManager;
import com.yunshipei.core.net.EnterClient;
import com.yunshipei.enterplorer.BuildConfig;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.EnterDbManager;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.utils.CrashHandler;

import java.io.InputStream;

import io.rong.app.DemoContext;
import io.rong.app.RongCloudEvent;
import io.rong.imkit.RongIM;
import io.rong.imlib.ipc.RongExceptionHandler;
import io.rong.push.RongPushClient;

public class EnterApplication extends MultiDexApplication {

    private static EnterApplication mApp;

    public static EnterApplication getApp() {
        return mApp;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initialize();
    }

    private void initialize() {
        mApp = this;
        ViewTarget.setTagId(R.id.glide_tag);
        YspPreferences.getInstance().init(this);

        //初始化Enterplorer SDK
        XCloudSDKManager.getInstance().init(this);

        SharedPreferences preferences = getSharedPreferences(Globals.NO_CLEAR_SHP, Context.MODE_PRIVATE);
        SharedPreferences yspPreferences = YspPreferences.getInstance().getSharedPreferences();

        /*
         * 初始化manager的代理和服务地址，避免内存启动到某个activity单例没有初始化，manager地址的设置方法是先获取手动设置的，如果没有手动设置的，则获取
         * 从hub请求到的。
         */
        String managerServer = preferences.getString(Globals.MANUAL_BASE_URL, "");
        if (TextUtils.isEmpty(managerServer)) {
            managerServer = preferences.getString(Globals.SP_HUB_GET_SERVER, "");
        }
        String proxy = preferences.getString(Globals.MANUAL_PROXY, "");
        int port = preferences.getInt(Globals.MANUAL_PROXY_PORT, 0);
        if (TextUtils.isEmpty(proxy) || port == 0) {
            proxy = yspPreferences.getString(Globals.SP_HUB_GET_PROXY_IP, "");
            port = yspPreferences.getInt(Globals.SP_HUB_GET_PROXY_PORT, 0);
        }
        EnterClient.getInstances().initManagerClient(managerServer + "/v2/newLogin", proxy, port);

        //manager代理初始化完毕，初始化manager接口请求，避免内存启动空指针异常
        HttpMethods.getInstance().initManagerServer(managerServer);

        //注册Glide的网络请求client，设置请求的client的代理
        OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory(EnterClient.getInstances().getManagerClient());
        Glide.get(this).register(GlideUrl.class, InputStream.class, factory);

        //初始化全局主题
        String themeCode = preferences.getString(Globals.SP_COMPANY_THEME_CODE, "1");
        EnterConfig.getInstance().setThemeCode(themeCode);

        //初始化数据库
        EnterDbManager.getInstances().init(this);

        //崩溃异常处理
        if (BuildConfig.DEBUG) {
            CrashHandler crashHandler = CrashHandler.getInstance();
            crashHandler.init(getApplicationContext());
        }

        //初始化融云相关功能
        RongPushClient.registerHWPush(this);
        RongPushClient.registerMiPush(this, Globals.MIPUSH_APPID, Globals.MIPUSH_APPKEY);
        RongIM.init(this);
        DemoContext.init(this);
        RongCloudEvent.init(this);
        Thread.setDefaultUncaughtExceptionHandler(new RongExceptionHandler(this));
    }

    /**
     * 项目定制开发时经常遇到不需要第一步登录的情况；
     * 如果第一步没有，只需要调用此方法设置manager地址，manager访问服务器代理服务器，企业域名，主题色，第二步登录用户名输入框的hint文字，第二步登录页面logo，
     * 这些内容都是从第一步登录获取的；
     * 企业域名，companyId等某些页面可能会从SharedPreference获取，所以定制项目直接从这里设置即可。
     */
    @SuppressLint("ApplySharedPref")
    private void initNoneCompanyNameLogin(@NonNull String managerServer, @NonNull String companyName, @NonNull String companyId, String logoUrl, String proxyIP, String proxyPort, String themeCode, String placeHolder) {
        SharedPreferences preferences = getSharedPreferences(Globals.NO_CLEAR_SHP, Context.MODE_PRIVATE);
        preferences.edit()
                .putString(Globals.MANUAL_BASE_URL, managerServer)
                .putString(Globals.SP_COMPANY_HOST, companyName)
                .putString(Globals.SP_COMPANY_ID, companyId)
                .putString(Globals.SP_COMPANY_LOGO, logoUrl)
                .putString(Globals.MANUAL_PROXY, proxyIP)
                .putString(Globals.MANUAL_PROXY_PORT, proxyPort)
                .putString(Globals.SP_COMPANY_THEME_CODE, themeCode)
                .putString(Globals.SP_COMPANY_PLACE_HOLDER, placeHolder)
                .commit();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        RongIM.getInstance().logout();
        sendBroadcast(new Intent(Globals.ACTION_FINISH_BASE_ACTIVITY));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Process.killProcess(Process.myPid());
            }
        }, 800);
    }
}
